//
//  RTJHomeHeaderView.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/11/27.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJHomeHeaderView.h"
#import "RTJCustomButton.h"
#import "RTJChargeRootController.h"
#import "RTJInvitationController.h"
#import "RTJInformationController.h"
#import "RTJHomeNoticeController.h"

#import "WSLRollView.h"

#define KRollViewHeight 20

@interface WSLRollViewVerticalCell : WSLRollViewCell

@property (strong, nonatomic) UILabel * titleLabel;

@end

@implementation WSLRollViewVerticalCell
- (instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        
        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.textAlignment = NSTextAlignmentLeft;
        self.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:11];
        self.titleLabel.textColor = [UIColor colorForHex:@"#666666"];
        self.titleLabel.userInteractionEnabled = YES;
        [self.contentView addSubview:self.titleLabel];
        self.contentView.clipsToBounds = YES;
    }
    return self;
}
- (void)refreshData{
    
    self.titleLabel.frame = CGRectMake(45, 0, self.frame.size.width, self.frame.size.height);
}
@end

@interface RTJHomeHeaderView() <HAutoScrollViewDelegate,HAutoScrollViewDataSource,WSLRollViewDelegate,UIScrollViewDelegate>{
    
    NSMutableArray * _array;

}
@property (strong, nonatomic)  HAutoScrollView *autoView;
//@property (weak, nonatomic) IBOutlet UIView *scView;
//@property (weak, nonatomic) IBOutlet UIView *bg_view;
@property (strong, nonatomic)WSLRollView * pageRollView;
@property (strong, nonatomic) UIViewController * homeVC;
@property (nonatomic,strong)UIScrollView * scrollView;

@end


@implementation RTJHomeHeaderView

+(instancetype)loadNib {
    
    return [[NSBundle mainBundle] loadNibNamed:@"RTJHomeHeaderView" owner:self options:nil].firstObject;
}

-(void)awakeFromNib {
    [super awakeFromNib];
           self.backgroundColor = [UIColor whiteColor];
    
}

-(void)layoutSubviews {
  
    [super layoutSubviews];
    
    [self setSize:CGSizeMake(screenW, screenH == 812 ? screenH*240/667:screenH*270/667)];
    
    _autoView = [[HAutoScrollView alloc]init];
    _autoView.delegate = self;
    _autoView.dataSource = self;
    _autoView.autoFlip = true;
    _autoView.flipInterval = 2.0;
    _autoView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_autoView];

    CGFloat topH = 0;
    
    if (screenH < 812) {
        
        topH = -20;
        
    }else if(screenH == 812){
        
         topH = -24;
        
    }else{
        
         topH = -44;
    }
    
    [_autoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(topH);
        make.right.equalTo(0);
        make.left.equalTo(0);
        make.height.equalTo(screenH*188/667);
    }];
    
    CGFloat H = screenH == 812 ? 80:60;
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake( screenW-95, (screenH*188/667) - H, 90, 15)];
    lab.text = @"网贷有风险 出借需谨慎";
    lab.textColor = [UIColor whiteColor];
    lab.textAlignment =  NSTextAlignmentCenter;
    lab.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:7];
    [_autoView addSubview:lab];

    UIView *viewBottom = [[UIView alloc]initWithFrame:CGRectZero];
    viewBottom.layer.cornerRadius=10;
    viewBottom.layer.shadowColor=[UIColor colorForHex:@"#dbc9cc"].CGColor;
    viewBottom.layer.shadowOffset=CGSizeMake(-1, 1);
    viewBottom.layer.shadowOpacity=0.5;
    viewBottom.layer.shadowRadius=5;
    viewBottom.backgroundColor = [UIColor whiteColor];

    [self addSubview:viewBottom];


    [viewBottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(-10);
        make.left.equalTo(10);
        make.height.equalTo(screenH*122/667);
        make.bottom.equalTo(self).offset(-12);
    }];
    
    // 每行个数
    int maxClos = 4;
    
    NSArray *titleArr = @[@"新手福利",@"我的邀请",@"信息披露"];
    for (int i = 0; i < 4 ; i ++) {
        
        // 行号
        CGFloat row = i / maxClos;
        // 列号
        CGFloat clo = i % maxClos;
        
        // x坐标之间间距
        CGFloat xMargin = screenW*20/375;
        // y坐标之间间距
        CGFloat yMargin = 0;
        
        CGFloat buttonW = (screenW-xMargin*5-screenW*20/375)/4;
        CGFloat buttonH = screenH*60/667;
        
        RTJCustomButton *btn = [RTJCustomButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(xMargin +clo*(buttonW + xMargin),screenH*20/667 +row*(yMargin+buttonH),buttonW, buttonH);
        btn.tag = i +10;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor:[UIColor colorForHex:@"#333333"] forState:UIControlStateNormal];
        
        if (btn.tag == 13) {
            
            if ([RTJUserTool getTheUserModel].has_sign == 1) {
                
                btn.userInteractionEnabled = NO;
                [btn setImage:[UIImage imageNamed:@"每日签到"] forState:UIControlStateNormal];
                [btn setTitle:@"签到成功" forState:UIControlStateNormal];

            }else{
                
                btn.userInteractionEnabled = YES;
                [btn setImage:[UIImage imageNamed:@"mrqdweiqiandao"] forState:UIControlStateNormal];
                [btn setTitle:@"每日签到" forState:UIControlStateNormal];

            }
            
        }else{
            
            [btn setImage:[UIImage imageNamed:titleArr[i]] forState:UIControlStateNormal];
            [btn setTitle:titleArr[i] forState:UIControlStateNormal];
            
        }
        
        [viewBottom addSubview:btn];

    }
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10, screenH*40/667+screenH*40/667, screenW- screenW*40/375, 1)];
    line.backgroundColor = [UIColor colorForHex:@"#E6E6E6"];
    [viewBottom addSubview:line];
    
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(10, line.frame.size.height+line.y+13, 15, 15)];
    img.image = [UIImage imageNamed:@"线性_喇叭"];
    [viewBottom addSubview:img];
    
    
    WSLRollView * pageRollView = [[WSLRollView alloc] initWithFrame:CGRectMake(img.x+img.width,line.frame.size.height+line.y+13 , screenW- 2*screenW*35/375, 15)];
    pageRollView.sourceArray = [NSMutableArray arrayWithArray:_array];
    pageRollView.backgroundColor = [UIColor whiteColor];
    pageRollView.scrollStyle = WSLRollViewScrollStylePage;
    pageRollView.scrollDirection = UICollectionViewScrollDirectionVertical;
    pageRollView.interval = 2;
    pageRollView.delegate = self;
    
    
    [pageRollView registerClass:[WSLRollViewVerticalCell class] forCellWithReuseIdentifier:@"PageRollID"];
    [viewBottom addSubview:pageRollView];
    _pageRollView = pageRollView;
    
}

-(void)btnAction:(UIButton *)btn{
    
    if (btn.tag == 12) {
        
        RTJInformationController *vc = [[RTJInformationController alloc]init];
        [_homeVC.navigationController pushViewController:vc animated:YES];
        
    }else{
        
        if ([RTJUserTool isLogin]) {
            
            if (btn.tag == 10) {
                
                RTJChargeRootController *vc = [[RTJChargeRootController alloc]init];
                vc.isUserCenter = YES;
                [_homeVC.navigationController pushViewController:vc animated:YES];
                
            }else if (btn.tag == 11){
                
                RTJInvitationController *vc = [[RTJInvitationController alloc]init];
                [_homeVC.navigationController pushViewController:vc animated:YES];
                
            }else if (btn.tag == 13){
                
                [SVProgressHUD  showWithStatus:nil];
                
                [RTJNetWork asyncRequestWithURL:@"user/sign_in" params:nil method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
                    
                    [SVProgressHUD dismiss];
                    
                    if (success) {
                        
                        if ([data[@"status"]integerValue] == 1) {
                            
                            [btn setImage:[UIImage imageNamed:@"每日签到"] forState:UIControlStateNormal];
                            btn.userInteractionEnabled = NO;
                            [btn setTitle:@"签到成功" forState:UIControlStateNormal];
                            
                            RTJUserModel *model = [RTJUserTool getTheUserModel];
                            model.has_sign = 1;
                            [RTJUserTool saveUserInfo:model];
                            
                            [SVProgressHUD showSuccessWithStatus:data[@"msg"]];
                            
                        }else{
                            
                            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                            
                        }
                        
                    }else{
                        
                        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
                        
                    }
                    
                }];
                
            }
            
        }else{
            
            RTJLoginOrRegisterController *vc = [[RTJLoginOrRegisterController alloc]init];
            LXNavigationViewController *nav=[[LXNavigationViewController alloc]initWithRootViewController:vc];
            [_homeVC presentViewController:nav animated:YES completion:nil];
        }
    }
}

#pragma mark - WSLRollViewDelegate

//返回itemSize
- (CGSize)rollView:(WSLRollView *)rollView sizeForItemAtIndex:(NSInteger)index{
    if (rollView.scrollStyle == WSLRollViewScrollStylePage){
        return CGSizeMake(screenW, 150);
    }else{
        NSNumber * width = _array[index][@"width"];
        NSNumber * height = _array[index][@"height"];
        return CGSizeMake([width floatValue], [height floatValue]);
    }
}

//间隔
- (CGFloat)spaceOfItemInRollView:(WSLRollView *)rollView{
    if (rollView.scrollStyle == WSLRollViewScrollStylePage){
        return 0;
    }else{
        return 10;
    }
}

//内边距
- (UIEdgeInsets)paddingOfRollView:(WSLRollView *)rollView{
    if (rollView.scrollStyle == WSLRollViewScrollStylePage){
        return UIEdgeInsetsMake(0,0,0,0);
    }else{
        return UIEdgeInsetsMake(0,0,0,0);
    }
}

//点击事件
- (void)rollView:(WSLRollView *)rollView didSelectItemAtIndex:(NSInteger)index{
//    WSL_Log(@" 点击了 %ld",index);
    
    RTJHomeNoticeController *vc = [[RTJHomeNoticeController alloc]init];
    [_homeVC.navigationController pushViewController:vc animated:YES];
    
}

//当前页码
- (void)rollView:(WSLRollView *)rollView didRollItemToIndex:(NSInteger)currentIndex{
//    WSL_Log(@"当前页码 %ld",currentIndex);
}

//返回自定义cell样式
-(WSLRollViewCell *)rollView:(WSLRollView *)rollView cellForItemAtIndex:(NSInteger)index{
    
    WSLRollViewVerticalCell * cell;
    if (rollView.scrollStyle == WSLRollViewScrollStylePage){
        cell = (WSLRollViewVerticalCell *)[rollView dequeueReusableCellWithReuseIdentifier:@"PageRollID" forIndex:index];
    }else{
        cell = (WSLRollViewVerticalCell *)[rollView dequeueReusableCellWithReuseIdentifier:@"StepRollID" forIndex:index];
    }
    cell.backgroundColor = _array[index][@"color"];
    cell.titleLabel.text = _array[index][@"title"];
    [cell refreshData];
    
    return cell;
}

#pragma mark - 刷新数据
- (void)loadData:(NSMutableArray *)array noticelist:(NSArray *)noticelist HomeVC:(nonnull UIViewController *)HomeVC{
    
     _homeVC = HomeVC;
    _dataSource = [array mutableCopy];
    _array = [NSMutableArray array];
    for (int i = 0 ; i < noticelist.count; i++) {
        [_array addObject:@{@"title":[NSString stringWithFormat:@"%@",noticelist[i][@"title"]],@"color":[UIColor whiteColor],@"height":@(20),@"width":@(screenW-2*screenW*35/375)}];
    }
    _pageRollView.sourceArray = [NSMutableArray arrayWithArray:noticelist];
    [_pageRollView reloadData];

    [self.autoView reloadData];
    
}

#pragma mark - HAutoScrollViewDelegate
-(void)autoScrollView:(HAutoScrollView *)asView
 didSelectAtPageIndex:(NSInteger)pIndex {
    if (_delegate != nil && [_delegate respondsToSelector:@selector(didSelectedAutoScrollView:pageIndex:)]){
        [_delegate didSelectedAutoScrollView:asView pageIndex:pIndex];
    }
}

#pragma mark - HAutoScrollViewDataSource
-(NSInteger)numberOfPagesInHAutoScrollView:(HAutoScrollView *)asView{
    return self.dataSource.count;
}

-(UIView *)pageAtIndex:(NSInteger)index
        autoScrollView:(HAutoScrollView *)asView{
    UIImageView *imgv = [[UIImageView alloc]init];
//    imgv.contentMode = UIViewContentModeScaleAspectFit;
    imgv.clipsToBounds = true;
    imgv.backgroundColor = [UIColor blueColor];
//    imgv.image = [UIImage imageNamed:@"banner_jzy"];
//    ZXBannerModel *model = self.dataSource[index];
    [imgv sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,_dataSource[index][@"img"]]] placeholderImage:[UIImage imageNamed:@"banner_jzy"]];
    return imgv;
}

#pragma mark - lazy
//-(HAutoScrollView *)autoView {
//    if (!_autoView) {
//        _autoView = [[HAutoScrollView alloc]init];
//        _autoView.delegate = self;
//        _autoView.dataSource = self;
//        _autoView.autoFlip = true;
//        _autoView.flipInterval = 2.0;
//       _autoView.backgroundColor = [UIColor yellowColor];
//
//    }
//    return _autoView;
//}

-(NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]initWithCapacity:3];
    }
    return _dataSource;
}

@end
